<template>
  <div id="bonusPage">
    <!-- 使用麵包屑組件 -->
    <BreadcrumbComponent :breadcrumbItems="breadcrumbItems" />
    <!-- 表格篩選 -->
    <TableFilter :config="filterConfig" @search="handleSearch" />
    <!-- 工具欄 -->
    <a-space>
      <a-dropdown>
        <a-button type="default" :loading="exportLoading">
          <template #icon>
            <ExportOutlined />
          </template>
          導出
        </a-button>
        <template #overlay>
          <a-menu @click="handleExport">
            <a-menu-item key="filteredData"> 按篩選導出 </a-menu-item>
            <a-menu-item key="allData"> 全部導出 </a-menu-item>
          </a-menu>
        </template>
      </a-dropdown>
    </a-space>
    <div class="data-box">
      <a-table
        :columns="columns"
        :data-source="tableData"
        :pagination="pagination"
        :loading="loading"
        :scroll="{ x: 1500, y: 420 }"
      >
        <!-- 表格頭部 -->
        <template #headerCell="{ column }">
          <!-- 根據表頭字段進行表頭修飾 -->
        </template>

        <!-- 表格內容 -->
        <template #bodyCell="{ column, record }">
          <!-- 根據不同的列顯示不同的內容修飾 -->
          <template v-if="column.dataIndex === 'shop'">
            {{ record.shopName }}({{ record.shopId }})
          </template>
          <template v-if="column.dataIndex === 'totalSalesAmount'">
            $ {{ record.totalSalesAmount.toLocaleString() }}
          </template>
          <template v-if="column.dataIndex === 'shopSalesAmount'">
            $ {{ record.shopSalesAmount.toLocaleString() }}
          </template>
          <template v-if="column.dataIndex === 'shopRatio'">
            {{
              (
                (record.shopSalesAmount / record.totalSalesAmount) *
                100
              ).toFixed(2)
            }}%
          </template>

          <template v-if="column.dataIndex === 'bonusAmount'">
            <template v-if="isDoctor && !record.isArchived">待計算</template>
            <template v-else
              >$ {{ record.bonusAmount.toLocaleString() }}</template
            >
          </template>

          <template v-if="column.dataIndex === 'isArchived'">
            <a-tag
              :bordered="false"
              color="success"
              v-if="record.isArchived == true"
              >已歸檔</a-tag
            >
            <a-tag :bordered="false" color="processing" v-else>未歸檔</a-tag>
          </template>
          <template v-if="column.dataIndex === 'updatedAt'">
            {{ $formatDate(record.updatedAt) }}
          </template>
          <template v-if="column.key === 'action'">
            <a-button @click="handleView(record)">查看</a-button>
          </template>
        </template>
      </a-table>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref } from "vue";
import { message } from "ant-design-vue";
import { ExportOutlined } from "@ant-design/icons-vue";
import { bonusApi } from "@/api";
import BreadcrumbComponent from "@/components/BreadcrumbComponent.vue";
import TableFilter from "@/components/TableFilter.vue";
import { tableColumns, filterFields } from "@/models/bonus";
import { useRouter, useRoute } from "vue-router";
import { createPagination } from "@/utils/pagination";
import { watchRouteQuery } from "@/utils/routeQueryWatcherUtil";
import { useAuthUserStore } from "@/store/authUserStore";

/******* 頁面狀態與配置 *****************************/
const breadcrumbItems = [{ url: "", name: "獎金管理" }];
const columns = tableColumns;
const filterConfig = filterFields;
const router = useRouter();
const route = useRoute();
const loading = ref(false);
// 分頁配置
const pagination = createPagination();
// 數據
const tableData = ref([]);

const userInfo = useAuthUserStore().userInfo;
const isDoctor = userInfo.roles.includes("Doctor");

/******* 數據獲取與初始化 *****************************/
const fetchData = async (params?: any) => {
  loading.value = true; // 開始加載
  try {
    const {
      data: { list, page, limit, total },
    } = await bonusApi.getBonusList(params);
    tableData.value = list || [];
    pagination.updatePagination(page, limit, total);
  } catch (error) {
    console.error("獲取獎金列表失敗", error);
  } finally {
    loading.value = false; // 結束加載
  }
};

// 頁面加載時初始化數據
watchRouteQuery(fetchData);

/******* 獎金操作處理 *****************************/
// 搜索
const handleSearch = (params: any) => {
  router.push({ query: params });
};

// 查看
const handleView = (record: any) => {
  router.push({ name: "BonusDetail", params: { id: record.id } });
};

// 導出
const exportLoading = ref(false);
const handleExport = async ({ key }: { key: string }) => {
  let params: any = {};
  if (key === "filteredData") {
    params = route.query; // 導出篩選後的數據
  }
  exportLoading.value = true;
  try {
    await bonusApi.exportBonusList(params);
  } catch (error) {
    message.error("導出數據失敗");
  } finally {
    exportLoading.value = false; // 結束加載
  }
};
</script>

<style scoped></style>
